
/****************************************************************************/
/*Copyright (c) 2011, Florent DEVILLE.                                      */
/*All rights reserved.                                                      */
/*                                                                          */
/*Redistribution and use in source and binary forms, with or without        */
/*modification, are permitted provided that the following conditions        */
/*are met:                                                                  */
/*                                                                          */
/* - Redistributions of source code must retain the above copyright         */
/*notice, this list of conditions and the following disclaimer.             */
/* - Redistributions in binary form must reproduce the above                */
/*copyright notice, this list of conditions and the following               */
/*disclaimer in the documentation and/or other materials provided           */
/*with the distribution.                                                    */
/* - The names of its contributors cannot be used to endorse or promote     */
/*products derived from this software without specific prior written        */
/*permission.                                                               */
/* - The source code cannot be used for commercial purposes without         */ 
/*its contributors' permission.                                             */
/*                                                                          */
/*THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       */
/*"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT         */
/*LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS         */
/*FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE            */
/*COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,       */
/*INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,      */
/*BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;          */
/*LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER          */
/*CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT        */
/*LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN         */
/*ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE           */
/*POSSIBILITY OF SUCH DAMAGE.                                               */
/****************************************************************************/

#include "CPrimTriangle.h"
#include <cstring>

#include "RTMatrix33.h"

CPrimTriangle::CPrimTriangle():IPrimitive()
{
}

CPrimTriangle::CPrimTriangle(CVector3f* v):IPrimitive()
{
	//copy the vertices
	memcpy(m_vertex, v, 3*sizeof(CVector3f));

	//calculate the normal
	m_normal = (m_vertex[1] - m_vertex[0]).cross(m_vertex[2] - m_vertex[0]);
	m_normal.normalize();
}

CPrimTriangle::CPrimTriangle(CVector3f v1, CVector3f v2, CVector3f v3):IPrimitive()
{
	//copy the vertices
	m_vertex[0] = v1;
	m_vertex[1] = v2;
	m_vertex[2] = v3;

	//calculate the normal
	m_normal = (m_vertex[1] - m_vertex[0]).cross(m_vertex[2] - m_vertex[0]);
	m_normal.normalize();
}

//destructor
CPrimTriangle::~CPrimTriangle(){}

//add a vertex
void CPrimTriangle::addVertex(const CVector3f& v, int id)
{
	m_vertex[id] = v;
}

//add a uv texture coordinate
void CPrimTriangle::addUV(const CVector3f& v, int id)
{
	m_UV[id] = v;
}

//set triangle's normal
void CPrimTriangle::setNormal(const CVector3f& n)
{
	m_normal = n;
}

//calculate the normal
void CPrimTriangle::computeNormal()
{
	//calculate the normal
	m_normal = (m_vertex[1] - m_vertex[0]).cross(m_vertex[2] - m_vertex[0]);
	m_normal.normalize();
}

//precompute some value to make calculation faster
void CPrimTriangle::preCompute()
{
	_useTranslation = false;

	//calculate D
	RTMatrix33 mD(m_vertex[0], m_vertex[1], m_vertex[2]); 
	_D = mD.det();

	//if D = 0, then the triangle is on the plane x=0 or y=0 or z=0 or a point is on (0, 0, 0) so we translate everything
	_offset = CVector3f(0, 0, 0);
	while (_D == 0)
	{
		_useTranslation = true;
		_offset = _offset + CVector3f(1, 1, 1);
		_uvTranslated[0] = m_vertex[0] + _offset;
		_uvTranslated[1] = m_vertex[1] + _offset;
		_uvTranslated[2] = m_vertex[2] + _offset;
		mD.setColumns(_uvTranslated[0], _uvTranslated[1], _uvTranslated[2]); 
		_D = mD.det();
	}
}

bool CPrimTriangle::intersect(const CRay& ray, float& dist, bool useGlobalCoordinates)
{
	//change the coordinate system
	CRay modRay;
	if (useGlobalCoordinates)
		globalToLocal(ray, modRay);
	else
		convertRayToLocalCoordinates(ray, modRay);


	CVector3f w(modRay.getOrigin().x - m_vertex[0].x, modRay.getOrigin().y - m_vertex[0].y, 
		modRay.getOrigin().z - m_vertex[0].z);

	CVector3f u = m_vertex[1] - m_vertex[0];
	CVector3f v = m_vertex[2] - m_vertex[0];

	float D = -(u.cross(v)).dot(modRay.getDirection());
	float a = -(w.cross(v)).dot(modRay.getDirection()) / D;
	float b = -(u.cross(w)).dot(modRay.getDirection()) / D;

	dist = (u.cross(v)).dot(w) / D;

	if(dist <= 0)
		return false;

	if(a > 0 && b > 0 && a+b <= 1)
		return true;

	return false;

}

//calculate if there is an intersextion between the ray and the triangle. The ray must be in triangle local space.
bool CPrimTriangle::intersectLocalSpace(const CRay& ray, float& dist)
{
	CVector3f w(ray.getOrigin().x - m_vertex[0].x, ray.getOrigin().y - m_vertex[0].y, 
		ray.getOrigin().z - m_vertex[0].z);

	CVector3f u = m_vertex[1] - m_vertex[0];
	CVector3f v = m_vertex[2] - m_vertex[0];

	float D = -(u.cross(v)).dot(ray.getDirection());
	float a = -(w.cross(v)).dot(ray.getDirection()) / D;
	float b = -(u.cross(w)).dot(ray.getDirection()) / D;

	dist = (u.cross(v)).dot(w) / D;

	if(dist <= 0)
		return false;

	if(a > 0 && b > 0 && a+b <= 1)
		return true;

	return false;
}

void CPrimTriangle::computeNormal(const CRay& ray, float /*dist*/, CVector3f& normal)const
{
	//change the coordinate system
	CRay R;
	convertRayToLocalCoordinates(ray, R);

	normal = m_normal;
	//if(ray.getDirection().dot(normal) > 0)
	//	normal *= -1;

	convertNormalToGlobalCoordinates(normal, normal);
}

bool CPrimTriangle::isInside(const CVector3f& p)const
{
	//convert p to local coordinates
	CVector3f localP;
	convertPointToLocalCoordinates(p, localP);

    if (sameSide(p, m_vertex[0], m_vertex[1], m_vertex[2]) && sameSide(p, m_vertex[1], m_vertex[0], m_vertex[2])
        && sameSide(p, m_vertex[2], m_vertex[0], m_vertex[1])) 
		return true;
    
	return false;
}

//get a pointer to the vertex array
CVector3f* CPrimTriangle::getVertices()
{
	return m_vertex;
}

//get a pointer to the uv map array
CVector3f* CPrimTriangle::getUV()
{
	return m_UV;
}

bool CPrimTriangle::sameSide(const CVector3f& p1, const CVector3f& p2, const CVector3f& a, const CVector3f& b)const
{
	CVector3f cp1 = (b-a).cross(p1-a);
	CVector3f cp2 = (b-a).cross(p2-a);
    if(cp1.dot(cp2) >= 0)
		return true;

    return false;
}
